const { BaseController } = require('../Base')

class MrGame extends BaseController {
  constructor() {
    super()
    this.dirPath = this.path.resolve(__dirname, '../../public/upload/count')
  }
  // 登录获取token
  login(ctx) {
    const valiList = [
      { name: 'username', msg: '用户名不能为空!' },
      { name: 'password', msg: '密码不能为空!' }
    ]
    let validate = this.tools.validate(ctx.request.body, valiList)
    if (validate) {
      return (ctx.body = this.resError(validate))
    }
    const username = ctx.request.body.username
    const password = ctx.request.body.password
    /**
     * 用户名和密码只有一个 ^_^
     */
    if (username == 'admin' && password == '1564677900') {
      const token = this.tools.jwt.jwtToken(ctx.request.body)
      ctx.body = this.resSuccess(token)
    } else {
      ctx.body = this.resError('用户名或密码错误')
    }
  }
  // 登录获取用户信息，权限信息 - 根据 token
  getUserInfo(ctx) {
    let token = this.tools.getToken(ctx)
    let userInfo = this.tools.jwt.jwtVerify(token).decoded
    ctx.body = this.resSuccess(userInfo)
  }
  /**
   * game 相关
   */
  /**日志记录 */
  async gameCount(ctx) {
    let body = ctx.request.body
    await this.tools.file.checkDir(this.dirPath)
    let id = `${Date.now()}-${this.tools.guid().slice(0, 6)}`
    const filePath = this.path.join(this.dirPath, `${id}.json`)
    body.id = id
    body.ip = ctx.request.ip
    this.fs.writeFileSync(filePath, JSON.stringify(body))
    ctx.body = this.resSuccess('保存成功')
  }
  /**获取统计日志 */
  async getLogs(ctx) {
    let fileList = this.tools.file.getFileFlatList(this.dirPath)
    let list = []
    for (let item of fileList) {
      let content = require(item.filePath)
      list.push(content)
    }
    ctx.body = this.resSuccess(list)
  }
  /**删除统计日志 */
  async removeLogById(ctx) {
    const id = ctx.query.id
    if (!id) {
      return (ctx.body = this.resError('未传入有效id'))
    }
    try {
      this.fs.unlinkSync(this.path.join(this.dirPath, `${id}.json`))
      ctx.body = this.resSuccess(`${id} 删除成功`)
    } catch (error) {
      ctx.body = this.resError(`${id} 未找到`)
    }
  }
  /**清空所有统计日志 */
  async clearAllLog(ctx) {
    let fileList = this.tools.file.getFileFlatList(this.dirPath)
    for (let item of fileList) {
      this.fs.unlinkSync(item.filePath)
    }
    ctx.body = this.resSuccess('删除完成')
  }
}
const ex = new MrGame()
module.exports = ex
